"""
管理员端WebSocket聊天处理器
"""
import datetime
from flask import request, session
from flask_socketio import emit, join_room, leave_room
from apps.extensions.init_websocket import socketio
from apps.extensions import db
from apps.modules.admin.models.cms.cms_chat import ChatRecord, ChatSession
import logging
logger = logging.getLogger(__name__)
logger.info("正在加载管理员端WebSocket处理器...")

# 跟踪在线的管理员
online_admins = set()

@socketio.on('connect', namespace='/admin/chat')
def on_admin_connect():
    """管理员连接"""
    admin_id = session.get('user_id', 'unknown')
    online_admins.add(admin_id)
    logger.info(f"管理员连接: {admin_id}, 当前在线管理员: {len(online_admins)} 个")
    emit('connect_response', {'msg': '管理员连接成功', 'sid': request.sid})


@socketio.on('disconnect', namespace='/admin/chat')
def on_admin_disconnect():
    """管理员断开连接"""
    admin_id = session.get('user_id', 'unknown')
    online_admins.discard(admin_id)
    logger.info(f"管理员断开连接: {admin_id}, 当前在线管理员: {len(online_admins)} 个")


@socketio.on('test_admin_connection', namespace='/admin/chat')
def on_test_admin_connection():
    """测试管理员连接"""
    try:
        logger.info(f"收到管理员测试连接请求: {request.sid}")
        emit('test_response', {'msg': '管理员连接测试成功', 'sid': request.sid})
    except Exception as e:
        logger.error(f"管理员测试连接错误: {e}")


@socketio.on('join_admin_room', namespace='/admin/chat')
def on_join_admin_room():
    """加入管理员监控房间"""
    try:
        join_room('admin_room')
        emit('joined_admin_room', {'msg': '已加入管理员房间'})
        logger.info(f"管理员 {request.sid} 加入监控房间")
    except Exception as e:
        logger.error(f"加入管理员房间错误: {e}")
        emit('error', {'msg': '加入管理员房间失败'})


@socketio.on('monitor_session', namespace='/admin/chat')
def on_monitor_session(data):
    """监控指定会话"""
    try:
        session_id = data.get('session_id')
        if session_id:
            join_room(session_id)
            emit('monitoring_session', {'session_id': session_id})
            logger.info(f"管理员 {request.sid} 开始监控会话 {session_id}")
    except Exception as e:
        logger.error(f"监控会话错误: {e}")
        emit('error', {'msg': '监控会话失败'})


@socketio.on('send_admin_message', namespace='/admin/chat')
def on_send_admin_message(data):
    """管理员发送消息"""
    try:
        session_id = data.get('session_id')
        content = data.get('content', '').strip()
        message_type = data.get('message_type', 'text')  # 新增：消息类型
        image_data = data.get('image_data')  # 新增：图片数据
        
        if not session_id or not content:
            emit('error', {'msg': '会话ID或消息内容不能为空'})
            return
        
        # 确保会话存在
        session = ChatSession.query.filter_by(session_id=session_id).first()
        if not session:
            logger.info(f"管理员发送消息失败: 会话 {session_id} 不存在")
            emit('error', {'msg': '会话不存在'})
            return
        
        # 保存消息记录
        # 对于图片消息，将base64数据存储到content字段
        content_to_save = image_data if message_type == 'image' and image_data else content
        
        new_record = ChatRecord(
            session_id=session_id,
            content=content_to_save,  # 文本消息存文本，图片消息存base64数据
            message_type=message_type,  # 保存消息类型
            user_name=session.user_name,  # 从会话中获取用户名
            user_phone=session.user_phone,  # 从会话中获取用户电话
            sender_type='admin',
            ip_address=session.ip_address,  # 从会话中获取IP地址
            user_agent=session.user_agent,  # 从会话中获取用户代理
            create_time=datetime.datetime.now()
        )
        db.session.add(new_record)
        
        # 更新会话消息数和最后更新时间
        session.message_count += 1
        session.update_time = datetime.datetime.now()
        
        db.session.commit()
        
        logger.info(f"管理员向会话 {session_id} 发送消息: {content}")
        
        # 准备发送数据
        message_data = {
            'content': content,
            'sender_type': 'admin',
            'message_type': message_type,
            'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 如果是图片消息，添加图片数据
        if message_type == 'image' and image_data:
            message_data['image_data'] = image_data
        
        # 发送消息到用户
        try:
            emit('new_message', message_data, room=session_id, namespace='/chat')
        except Exception as emit_error:
            logger.error(f"发送消息到用户失败: {emit_error}")
        
        # 通知管理员消息已发送
        sent_data = {
            'session_id': session_id,
            'content': content,
            'message_type': message_type,
            'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 如果是图片消息，添加图片数据
        if message_type == 'image' and image_data:
            sent_data['image_data'] = image_data
        
        emit('message_sent', sent_data)
        
    except Exception as e:
        logger.error(f"管理员发送消息错误: {e}")
        db.session.rollback()
        emit('error', {'msg': f'发送消息失败: {str(e)}'})
    finally:
        db.session.close()


@socketio.on('get_active_sessions', namespace='/admin/chat')
def on_get_active_sessions():
    """获取活跃会话列表"""
    try:
        # 查询所有活跃会话，按创建时间排序（避免update_time为null的问题）
        sessions = ChatSession.query.filter_by(status='active')\
                                  .order_by(ChatSession.start_time.desc()).all()
        
        logger.info(f"数据库查询到 {len(sessions)} 个活跃会话")
        
        session_list = []
        for session in sessions:
            # 处理可能为None的时间字段
            update_time_str = ''
            if session.update_time:
                update_time_str = session.update_time.strftime('%Y-%m-%d %H:%M:%S')
            
            session_data = {
                'session_id': session.session_id,
                'user_name': session.user_name or '匿名用户',
                'user_phone': session.user_phone or '',
                'message_count': session.message_count or 0,
                'start_time': session.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                'update_time': update_time_str,
                'status': session.status
            }
            session_list.append(session_data)
            
            logger.info(f"  会话: {session.session_id}, 用户: {session.user_name or '匿名'}, 消息数: {session.message_count}")
        
        emit('active_sessions', {'sessions': session_list})
        logger.info(f"向管理员发送 {len(session_list)} 个活跃会话")
        
    except Exception as e:
        logger.info(f"获取活跃会话错误: {e}")
        import traceback
        traceback.print_exc()
        emit('error', {'msg': '获取会话失败'})


@socketio.on('close_session', namespace='/admin/chat')
def on_close_session(data):
    """关闭会话"""
    try:
        session_id = data.get('session_id')
        if not session_id:
            emit('error', {'msg': '会话ID不能为空'})
            return
        
        # 更新会话状态
        session = ChatSession.query.filter_by(session_id=session_id).first()
        if session:
            session.status = 'closed'
            session.end_time = datetime.datetime.now()
            session.update_time = datetime.datetime.now()
            db.session.commit()
            
            # 通知用户会话已关闭
            try:
                emit('session_closed', {
                    'msg': '管理员已关闭会话'
                }, room=session_id, namespace='/chat')
            except Exception as emit_error:
                print(f"通知用户会话关闭失败: {emit_error}")
            
            # 通知管理员会话已关闭
            emit('session_closed', {
                'session_id': session_id,
                'msg': '会话已关闭'
            })
            
            logger.info(f"会话 {session_id} 已关闭")
        else:
            emit('error', {'msg': '会话不存在'})
            
    except Exception as e:
        logger.error(f"关闭会话错误: {e}")
        # 回滚数据库事务
        try:
            db.session.rollback()
        except:
            pass
        emit('error', {'msg': '关闭会话失败'})


@socketio.on('admin_typing', namespace='/admin/chat')
def on_admin_typing(data):
    """管理员正在输入"""
    try:
        session_id = data.get('session_id')
        if session_id:
            emit('admin_typing', {
                'msg': '客服正在输入...'
            }, room=session_id, namespace='/chat')
    except Exception as e:
        logger.error(f"管理员输入状态错误: {e}")


@socketio.on('admin_stop_typing', namespace='/admin/chat')
def on_admin_stop_typing(data):
    """管理员停止输入"""
    try:
        session_id = data.get('session_id')
        if session_id:
            emit('admin_stop_typing', {}, room=session_id, namespace='/chat')
    except Exception as e:
        logger.error(f"管理员停止输入状态错误: {e}")


@socketio.on('user_disconnected', namespace='/admin/chat')
def on_user_disconnected(data):
    """用户断开连接"""
    try:
        sid = data.get('sid')
        disconnect_time = data.get('disconnect_time')
        logger.info(f"用户 {sid} 断开连接，时间: {disconnect_time}")
        
        # 通知所有管理员有用户断开连接
        emit('user_disconnected', {
            'sid': sid,
            'disconnect_time': disconnect_time
        }, broadcast=True)
        
    except Exception as e:
        logger.error(f"处理用户断开连接失败: {e}")


@socketio.on('on_session_closed', namespace='/admin/chat')
def on_session_closed(data):
    """处理会话关闭事件"""
    try:
        session_id = data.get('session_id')
        if session_id:
            # 查找并更新会话状态
            session = ChatSession.query.filter_by(session_id=session_id).first()
            if session:
                session.status = 'closed'
                session.end_time = datetime.datetime.now()
                db.session.commit()
                logger.info(f"管理员关闭会话 {session_id}")
                
                # 广播给其他管理员
                emit('session_closed', {
                    'session_id': session_id,
                    'msg': '会话已关闭'
                }, namespace='/admin/chat', broadcast=True, include_self=False)
                
    except Exception as e:
        logger.error(f"处理会话关闭失败: {e}")
        db.session.rollback()


@socketio.on('admin_voice_call_answer', namespace='/admin/chat')
def on_admin_voice_call_answer(data):
    """管理员接听语音通话"""
    try:
        session_id = data.get('session_id')
        offer = data.get('offer')
        logger.info(f"管理员接听语音通话，会话ID: {session_id}")
        logger.info(f"Offer数据存在: {offer is not None}")
        if offer:
            logger.info(f"Offer类型: {offer.get('type')}")
        
        # 通知用户通话被接听，包含WebRTC offer
        emit_result = emit('voice_call_incoming', {
            'session_id': session_id,
            'from': 'admin',
            'offer': offer
        }, room=session_id, namespace='/chat')
        
        logger.info(f"向房间 {session_id} 发送 voice_call_incoming 事件，emit结果: {emit_result}")
        
    except Exception as e:
        logger.error(f"管理员接听语音通话失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('ice_candidate', namespace='/admin/chat')
def on_admin_ice_candidate(data):
    """处理管理员端ICE候选"""
    try:
        session_id = data.get('session_id')
        candidate = data.get('candidate')
        sender = data.get('sender')
        logger.info(f"收到管理员ICE候选，会话ID: {session_id}, 发送者: {sender}")
        
        # 转发ICE候选到用户端
        emit('ice_candidate', {
            'session_id': session_id,
            'candidate': candidate,
            'sender': sender
        }, room=session_id, namespace='/chat')
        
    except Exception as e:
        logger.error(f"处理管理员ICE候选失败: {e}")


@socketio.on('admin_voice_call_reject', namespace='/admin/chat')
def on_admin_voice_call_reject(data):
    """管理员拒绝语音通话"""
    try:
        session_id = data.get('session_id')
        reason = data.get('reason', 'rejected')
        message = data.get('message', '管理员拒绝了通话')
        logger.info(f"管理员拒绝语音通话，会话ID: {session_id}, 原因: {reason}")
        
        # 通知用户通话被拒绝
        emit('voice_call_rejected', {
            'session_id': session_id,
            'from': 'admin',
            'reason': reason,
            'message': message
        }, room=session_id, namespace='/chat')
        
        # 创建系统消息记录
        if reason == 'busy':
            system_message = "📞 用户通话请求（管理员正在通话中）"
        else:
            system_message = "📞 管理员拒绝通话请求"
        
        # 保存到数据库
        chat_record = ChatRecord(
            session_id=session_id,
            sender_type='system',
            content=system_message,
            message_type='system',
            create_time=datetime.datetime.now()
        )
        db.session.add(chat_record)
        db.session.commit()
        
        # 发送聊天消息通知
        emit('voice_call_notification', {
            'session_id': session_id,
            'type': 'busy_reject' if reason == 'busy' else 'reject',
            'content': system_message,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, namespace='/admin/chat', broadcast=True)
        
    except Exception as e:
        logger.error(f"管理员拒绝语音通话失败: {e}")
        db.session.rollback()


@socketio.on('admin_voice_call_end', namespace='/admin/chat')
def on_admin_voice_call_end(data):
    """管理员结束语音通话"""
    try:
        session_id = data.get('session_id')
        logger.info(f"管理员结束语音通话，会话ID: {session_id}")
        
        # 通知用户通话结束
        emit('voice_call_ended', {
            'session_id': session_id,
            'from': 'admin'
        }, room=session_id, namespace='/chat')
        
    except Exception as e:
        logger.error(f"管理员结束语音通话失败: {e}")


@socketio.on('admin_voice_call_callback', namespace='/admin/chat')
def on_admin_voice_call_callback(data):
    """管理员回拨用户"""
    try:
        session_id = data.get('session_id')
        callback_type = data.get('type', 'callback')
        logger.info(f"管理员回拨用户，会话ID: {session_id}, 类型: {callback_type}")
        
        # 通知用户管理员回拨（发送来电通知，不包含offer）
        emit_result = emit('voice_call_incoming', {
            'session_id': session_id,
            'from': 'admin',
            'type': 'callback',
            'message': '客服正在呼叫您'
        }, room=session_id, namespace='/chat')
        
        logger.info(f"管理员回拨请求已发送到会话: {session_id}, emit结果: {emit_result}")
        
    except Exception as e:
        logger.error(f"管理员回拨失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('admin_voice_call_cancel', namespace='/admin/chat')
def on_admin_voice_call_cancel(data):
    """管理员取消回拨"""
    try:
        session_id = data.get('session_id')
        reason = data.get('reason', 'cancelled')
        logger.info(f"管理员取消回拨，会话ID: {session_id}, 原因: {reason}")
        
        # 通知用户回拨被取消
        emit('voice_call_callback_cancelled', {
            'session_id': session_id,
            'from': 'admin',
            'reason': reason,
            'message': '管理员取消了回拨'
        }, room=session_id, namespace='/chat')
        
        logger.info(f"已通知用户回拨取消: {session_id}")
        
    except Exception as e:
        logger.error(f"管理员取消回拨失败: {e}")


@socketio.on('voice_call_queue_status', namespace='/admin/chat')
def on_voice_call_queue_status(data):
    """管理员发送队列状态给用户"""
    try:
        session_id = data.get('session_id')
        status = data.get('status')
        position = data.get('position')
        message = data.get('message')
        
        logger.info(f"发送队列状态给用户，会话ID: {session_id}, 位置: {position}, 状态: {status}")
        
        # 转发队列状态给用户
        emit('voice_call_queue_update', {
            'session_id': session_id,
            'status': status,
            'position': position,
            'message': message,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, room=session_id, namespace='/chat')
        
        logger.info(f"队列状态已发送给用户: {message}")
        
    except Exception as e:
        logger.error(f"发送队列状态失败: {e}")


@socketio.on('voice_call_notification', namespace='/admin/chat')
def on_voice_call_notification(data):
    """处理管理员端语音通话通知"""
    try:
        session_id = data.get('session_id')
        notification_type = data.get('type')
        content = data.get('content')
        timestamp = data.get('timestamp')
        
        logger.info(f"管理员语音通话通知，会话ID: {session_id}, 类型: {notification_type}")
        
        # 保存到数据库
        if session_id and content:
            chat_record = ChatRecord(
                session_id=session_id,
                sender_type='system',
                content=content,
                message_type='system',
                create_time=datetime.datetime.now()
            )
            db.session.add(chat_record)
            db.session.commit()
            logger.info(f"系统消息已保存到数据库: {content}")
        
        # 广播通知给所有管理员客户端
        emit('voice_call_notification', {
            'session_id': session_id,
            'type': notification_type,
            'content': content,
            'timestamp': timestamp
        }, namespace='/admin/chat', broadcast=True)
        
    except Exception as e:
        logger.error(f"处理语音通话通知失败: {e}")
        db.session.rollback()

@socketio.on('admin_video_call_answer', namespace='/admin/chat')
def on_admin_video_call_answer(data):
    """管理员接听视频通话"""
    try:
        session_id = data.get('session_id')
        offer = data.get('offer')
        logger.info(f"管理员接听视频通话，会话ID: {session_id}")
        logger.info(f"Video Offer数据存在: {offer is not None}")
        if offer:
            logger.info(f"Video Offer类型: {offer.get('type')}")
        
        # 通知用户视频通话被接听，包含WebRTC offer
        emit_result = emit('video_call_incoming', {
            'session_id': session_id,
            'from': 'admin',
            'offer': offer
        }, room=session_id, namespace='/chat')
        
        logger.info(f"向房间 {session_id} 发送 video_call_incoming 事件，emit结果: {emit_result}")
        
    except Exception as e:
        logger.error(f"管理员接听视频通话失败: {e}")
        import traceback
        traceback.print_exc()

@socketio.on('video_ice_candidate', namespace='/admin/chat')
def on_admin_video_ice_candidate(data):
    """处理管理员端视频ICE候选"""
    try:
        session_id = data.get('session_id')
        candidate = data.get('candidate')
        sender = data.get('sender')
        logger.info(f"收到管理员视频ICE候选，会话ID: {session_id}, 发送者: {sender}")
        
        # 转发视频ICE候选到用户端
        emit('video_ice_candidate', {
            'session_id': session_id,
            'candidate': candidate,
            'sender': sender
        }, room=session_id, namespace='/chat')
        
    except Exception as e:
        logger.error(f"处理管理员视频ICE候选失败: {e}")

@socketio.on('admin_video_call_reject', namespace='/admin/chat')
def on_admin_video_call_reject(data):
    """管理员拒绝视频通话"""
    try:
        session_id = data.get('session_id')
        reason = data.get('reason', 'rejected')
        message = data.get('message', '管理员拒绝了视频通话')
        logger.info(f"管理员拒绝视频通话，会话ID: {session_id}, 原因: {reason}")
        
        # 通知用户视频通话被拒绝
        emit('video_call_rejected', {
            'session_id': session_id,
            'from': 'admin',
            'reason': reason,
            'message': message
        }, room=session_id, namespace='/chat')
        
        # 创建系统消息记录
        if reason == 'busy':
            system_message = "📹 用户视频通话请求（管理员正在视频通话中）"
        else:
            system_message = "📹 管理员拒绝视频通话请求"
        
        # 保存到数据库
        chat_record = ChatRecord(
            session_id=session_id,
            sender_type='system',
            content=system_message,
            message_type='system',
            create_time=datetime.datetime.now()
        )
        db.session.add(chat_record)
        db.session.commit()
        
        # 发送聊天消息通知
        emit('video_call_notification', {
            'session_id': session_id,
            'type': 'busy_reject' if reason == 'busy' else 'reject',
            'content': system_message,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, namespace='/admin/chat', broadcast=True)
        
    except Exception as e:
        logger.error(f"管理员拒绝视频通话失败: {e}")
        db.session.rollback()

@socketio.on('admin_video_call_end', namespace='/admin/chat')
def on_admin_video_call_end(data):
    """管理员结束视频通话"""
    try:
        session_id = data.get('session_id')
        logger.info(f"管理员结束视频通话，会话ID: {session_id}")
        
        # 通知用户视频通话结束
        emit('video_call_ended', {
            'session_id': session_id,
            'from': 'admin'
        }, room=session_id, namespace='/chat')
        
    except Exception as e:
        logger.error(f"管理员结束视频通话失败: {e}")


@socketio.on('video_call_ended', namespace='/admin/chat')
def on_video_call_ended(data):
    """处理用户结束视频通话"""
    try:
        session_id = data.get('session_id')
        from_user = data.get('from', 'user')
        logger.info(f"收到用户结束视频通话事件，会话ID: {session_id}, 来自: {from_user}")
        
        # 通知管理员视频通话结束
        emit_result = emit('video_call_ended', {
            'session_id': session_id,
            'from': from_user
        }, namespace='/admin/chat', broadcast=True)
        
        logger.info(f"视频通话结束事件已广播给管理员，emit结果: {emit_result}")
        
    except Exception as e:
        logger.error(f"处理用户结束视频通话失败: {e}")
        import traceback
        traceback.print_exc()

@socketio.on('admin_video_call_callback', namespace='/admin/chat')
def on_admin_video_call_callback(data):
    """管理员回拨用户视频通话"""
    try:
        session_id = data.get('session_id')
        callback_type = data.get('type', 'callback')
        logger.info(f"管理员回拨用户视频通话，会话ID: {session_id}, 类型: {callback_type}")
        
        # 通知用户管理员回拨视频通话（发送来电通知，不包含offer）
        emit_result = emit('video_call_incoming', {
            'session_id': session_id,
            'from': 'admin',
            'type': 'callback',
            'message': '客服正在呼叫您视频通话'
        }, room=session_id, namespace='/chat')
        
        logger.info(f"管理员视频回拨请求已发送到会话: {session_id}, emit结果: {emit_result}")
        
    except Exception as e:
        logger.error(f"管理员视频回拨失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('admin_video_call_timeout', namespace='/admin/chat')
def on_admin_video_call_timeout(data):
    """管理员视频回拨超时"""
    try:
        session_id = data.get('session_id')
        logger.info(f"管理员视频回拨超时，会话ID: {session_id}")
        
        # 通知用户视频回拨超时
        emit('video_call_timeout', {
            'session_id': session_id,
            'from': 'admin',
            'message': '视频回拨超时，用户未接听'
        }, room=session_id, namespace='/chat')
        
        # 创建系统消息记录
        system_message = f"📞 视频回拨超时，用户未接听"
        
        # 保存到数据库
        chat_record = ChatRecord(
            session_id=session_id,
            sender_type='system',
            content=system_message,
            message_type='system',
            create_time=datetime.datetime.now()
        )
        db.session.add(chat_record)
        db.session.commit()
        
        logger.info(f"视频回拨超时通知已发送给用户: {session_id}")
        
    except Exception as e:
        logger.error(f"处理视频回拨超时失败: {e}")
        db.session.rollback()

@socketio.on('admin_video_call_cancel', namespace='/admin/chat')
def on_admin_video_call_cancel(data):
    """管理员取消视频回拨"""
    try:
        session_id = data.get('session_id')
        reason = data.get('reason', 'cancelled')
        logger.info(f"管理员取消视频回拨，会话ID: {session_id}, 原因: {reason}")
        
        # 通知用户视频回拨被取消
        emit('video_call_callback_cancelled', {
            'session_id': session_id,
            'from': 'admin',
            'reason': reason,
            'message': '管理员取消了视频回拨'
        }, room=session_id, namespace='/chat')
        
        logger.info(f"已通知用户视频回拨取消: {session_id}")
        
    except Exception as e:
        logger.error(f"管理员取消视频回拨失败: {e}")

@socketio.on('video_call_queue_status', namespace='/admin/chat')
def on_video_call_queue_status(data):
    """管理员发送视频通话队列状态给用户"""
    try:
        session_id = data.get('session_id')
        status = data.get('status')
        position = data.get('position')
        message = data.get('message')
        
        logger.info(f"发送视频通话队列状态给用户，会话ID: {session_id}, 位置: {position}, 状态: {status}")
        
        # 转发队列状态给用户
        emit('video_call_queue_update', {
            'session_id': session_id,
            'status': status,
            'position': position,
            'message': message,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, room=session_id, namespace='/chat')
        
        logger.info(f"视频通话队列状态已发送给用户: {message}")
        
    except Exception as e:
        logger.error(f"发送视频通话队列状态失败: {e}")

@socketio.on('video_call_notification', namespace='/admin/chat')
def on_video_call_notification(data):
    """处理管理员端视频通话通知"""
    try:
        session_id = data.get('session_id')
        notification_type = data.get('type')
        content = data.get('content')
        timestamp = data.get('timestamp')
        
        logger.info(f"管理员视频通话通知，会话ID: {session_id}, 类型: {notification_type}")
        
        # 保存到数据库
        if session_id and content:
            chat_record = ChatRecord(
                session_id=session_id,
                sender_type='system',
                content=content,
                message_type='system',
                create_time=datetime.datetime.now()
            )
            db.session.add(chat_record)
            db.session.commit()
            logger.info(f"系统消息已保存到数据库: {content}")
        
        # 广播通知给所有管理员客户端
        emit('video_call_notification', {
            'session_id': session_id,
            'type': notification_type,
            'content': content,
            'timestamp': timestamp
        }, namespace='/admin/chat', broadcast=True)
        
    except Exception as e:
        logger.error(f"处理视频通话通知失败: {e}")
        db.session.rollback()


# 桌面共享相关处理器

@socketio.on('desktop_share_incoming', namespace='/admin/chat')
def on_desktop_share_incoming(data):
    """管理员收到桌面共享请求"""
    try:
        session_id = data.get('session_id')
        user_info = data.get('user_info', {})
        timestamp = data.get('timestamp')
        logger.info(f"管理员收到桌面共享请求，会话ID: {session_id}, 用户信息: {user_info}")
        
        # 广播桌面共享请求给所有管理员客户端
        emit('desktop_share_incoming', {
            'session_id': session_id,
            'user_info': user_info,
            'timestamp': timestamp
        }, namespace='/admin/chat', broadcast=True)
        
        logger.info(f"桌面共享请求已广播给所有管理员")
        
    except Exception as e:
        logger.error(f"处理桌面共享请求失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('desktop_share_cancelled', namespace='/admin/chat')
def on_desktop_share_cancelled(data):
    """管理员收到桌面共享取消通知"""
    try:
        session_id = data.get('session_id')
        from_user = data.get('from', 'user')
        timestamp = data.get('timestamp')
        logger.info(f"管理员收到桌面共享取消通知，会话ID: {session_id}, 来自: {from_user}")
        
        # 广播桌面共享取消给所有管理员客户端
        emit('desktop_share_cancelled', {
            'session_id': session_id,
            'from': from_user,
            'timestamp': timestamp
        }, namespace='/admin/chat', broadcast=True)
        
        logger.info(f"桌面共享取消事件已广播给所有管理员")
        
    except Exception as e:
        logger.error(f"处理桌面共享取消失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('desktop_share_ended', namespace='/admin/chat')
def on_desktop_share_ended(data):
    """管理员收到桌面共享结束通知"""
    try:
        session_id = data.get('session_id')
        from_user = data.get('from', 'user')
        timestamp = data.get('timestamp')
        logger.info(f"管理员收到桌面共享结束通知，会话ID: {session_id}, 来自: {from_user}")
        
        # 广播桌面共享结束给所有管理员客户端
        emit('desktop_share_ended', {
            'session_id': session_id,
            'from': from_user,
            'timestamp': timestamp
        }, namespace='/admin/chat', broadcast=True)
        
        logger.info(f"桌面共享结束事件已广播给所有管理员")
        
    except Exception as e:
        logger.info(f"处理桌面共享结束失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('desktop_share_ice_candidate', namespace='/admin/chat')
def on_desktop_share_ice_candidate(data):
    """管理员收到桌面共享ICE候选"""
    try:
        session_id = data.get('session_id')
        candidate = data.get('candidate')
        sender = data.get('sender', 'user')
        logger.info(f"管理员收到桌面共享ICE候选，会话ID: {session_id}, 发送者: {sender}")
        
        # 转发ICE候选给用户
        emit('desktop_share_ice_candidate', {
            'session_id': session_id,
            'candidate': candidate,
            'sender': sender
        }, room=session_id, namespace='/chat')
        
        logger.info(f"桌面共享ICE候选已转发给用户")
        
    except Exception as e:
        logger.error(f"处理桌面共享ICE候选失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('desktop_share_missed', namespace='/admin/chat')
def on_desktop_share_missed(data):
    """桌面共享未接听"""
    try:
        session_id = data.get('session_id')
        user_info = data.get('user_info', {})
        logger.info(f"桌面共享未接听，会话ID: {session_id}")
        
        # 记录未接听消息到数据库
        try:
            session = ChatSession.query.filter_by(session_id=session_id).first()
            if session:
                system_record = ChatRecord(
                    session_id=session_id,
                    sender_type='system',
                    message_type='system',
                    content='桌面共享未接听',
                    create_time=datetime.datetime.now()
                )
                db.session.add(system_record)
                db.session.commit()
                print(f"桌面共享未接听系统消息已记录到数据库")
        except Exception as db_error:
            logger.error(f"记录桌面共享未接听系统消息失败: {db_error}")
            db.session.rollback()
        
        # 通知管理员桌面共享未接听
        emit('desktop_share_missed', {
            'session_id': session_id,
            'user_info': user_info,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, namespace='/admin/chat')
        
        logger.info(f"桌面共享未接听事件已发送给管理员")
        
    except Exception as e:
        logger.error(f"桌面共享未接听处理失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('desktop_share_offer', namespace='/admin/chat')
def on_desktop_share_offer(data):
    """处理桌面共享offer"""
    try:
        session_id = data.get('session_id')
        offer = data.get('offer')
        user_info = data.get('user_info', {})
        logger.info(f"收到桌面共享offer，会话ID: {session_id}")
        
        # 通知管理员收到桌面共享offer
        emit('desktop_share_offer_received', {
            'session_id': session_id,
            'offer': offer,
            'user_info': user_info,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, namespace='/admin/chat')
        
        logger.info(f"桌面共享offer已转发给管理员")
        
    except Exception as e:
        logger.error(f"处理桌面共享offer失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('admin_desktop_share_answer', namespace='/admin/chat')
def on_admin_desktop_share_answer(data):
    """管理员接听桌面共享"""
    try:
        session_id = data.get('session_id')
        answer = data.get('answer')
        logger.info(f"管理员接听桌面共享，会话ID: {session_id}")
        
        # 记录接听消息到数据库
        try:
            session = ChatSession.query.filter_by(session_id=session_id).first()
            if session:
                system_record = ChatRecord(
                    session_id=session_id,
                    sender_type='system',
                    message_type='system',
                    content='管理员已接听桌面共享',
                    create_time=datetime.datetime.now()
                )
                db.session.add(system_record)
                db.session.commit()
                logger.info(f"桌面共享接听系统消息已记录到数据库")
        except Exception as db_error:
            logger.error(f"记录桌面共享接听系统消息失败: {db_error}")
            db.session.rollback()
        
        # 通知用户管理员已接听桌面共享
        emit('desktop_share_accepted', {
            'session_id': session_id,
            'from': 'admin',
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, room=session_id, namespace='/chat')
        
        # 如果有answer数据，转发给用户
        if answer:
            emit('admin_desktop_share_answer', {
                'session_id': session_id,
                'answer': answer
            }, room=session_id, namespace='/chat')
            logger.info(f"桌面共享answer已转发给用户")
        
        logger.info(f"桌面共享接听事件已发送给用户")
        
    except Exception as e:
        logger.error(f"管理员接听桌面共享失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('admin_desktop_share_reject', namespace='/admin/chat')
def on_admin_desktop_share_reject(data):
    """管理员拒绝桌面共享"""
    try:
        session_id = data.get('session_id')
        reason = data.get('reason', 'rejected')
        logger.info(f"管理员拒绝桌面共享，会话ID: {session_id}, 原因: {reason}")
        
        # 记录拒绝消息到数据库
        try:
            session = ChatSession.query.filter_by(session_id=session_id).first()
            if session:
                system_record = ChatRecord(
                    session_id=session_id,
                    sender_type='system',
                    message_type='system',
                    content='管理员拒绝桌面共享',
                    create_time=datetime.datetime.now()
                )
                db.session.add(system_record)
                db.session.commit()
                logger.info(f"桌面共享拒绝系统消息已记录到数据库")
        except Exception as db_error:
            logger.error(f"记录桌面共享拒绝系统消息失败: {db_error}")
            db.session.rollback()
        
        # 通知用户管理员拒绝桌面共享
        emit('desktop_share_rejected', {
            'session_id': session_id,
            'from': 'admin',
            'reason': reason,
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, room=session_id, namespace='/chat')
        
        logger.info(f"桌面共享拒绝事件已发送给用户")
        
    except Exception as e:
        logger.error(f"管理员拒绝桌面共享失败: {e}")
        import traceback
        traceback.print_exc()


@socketio.on('admin_desktop_share_end', namespace='/admin/chat')
def on_admin_desktop_share_end(data):
    """管理员结束桌面共享"""
    try:
        session_id = data.get('session_id')
        logger.info(f"管理员结束桌面共享，会话ID: {session_id}")
        
        # 检查是否已经处理过这个会话的结束事件
        if hasattr(on_admin_desktop_share_end, 'processed_sessions'):
            if session_id in on_admin_desktop_share_end.processed_sessions:
                logger.info(f"会话 {session_id} 的结束事件已处理过，跳过")
                return
        else:
            on_admin_desktop_share_end.processed_sessions = set()
        
        # 添加到已处理集合
        on_admin_desktop_share_end.processed_sessions.add(session_id)
        
        # 记录结束消息到数据库
        try:
            session = ChatSession.query.filter_by(session_id=session_id).first()
            if session:
                system_record = ChatRecord(
                    session_id=session_id,
                    sender_type='system',
                    message_type='system',
                    content='管理员结束桌面共享',
                    create_time=datetime.datetime.now()
                )
                db.session.add(system_record)
                db.session.commit()
                logger.info(f"桌面共享结束系统消息已记录到数据库")
        except Exception as db_error:
            logger.error(f"记录桌面共享结束系统消息失败: {db_error}")
            db.session.rollback()
        
        # 通知用户管理员结束桌面共享
        emit('desktop_share_ended', {
            'session_id': session_id,
            'from': 'admin',
            'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }, room=session_id, namespace='/chat')
        
        logger.info(f"桌面共享结束事件已发送给用户")
        
        # 5秒后清理已处理记录，避免内存泄漏
        import threading
        def cleanup_processed_session():
            import time
            time.sleep(5)
            if hasattr(on_admin_desktop_share_end, 'processed_sessions'):
                on_admin_desktop_share_end.processed_sessions.discard(session_id)
        
        cleanup_thread = threading.Thread(target=cleanup_processed_session)
        cleanup_thread.daemon = True
        cleanup_thread.start()
        
    except Exception as e:
        logger.error(f"管理员结束桌面共享失败: {e}")
        import traceback
        traceback.print_exc()


logger.info("管理员端WebSocket处理器加载完成")